package com.flyfinger;

import com.flyfinger.conf.DataSourceConfig;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author zhouyp
 * @program auto-pull-conf
 * @description
 * @create 2020-06-24
 */
@SpringBootApplication
public class PullApplication {

	static CuratorFramework client;
	static CuratorCache cache;

	public static void main(String[] args) throws Exception {
		initZookeeper();
		SpringApplication.run(PullApplication.class, args);
	}

	public static void initZookeeper() throws Exception {
		String clientPath = "/jdbc-conf";
		String connectString = "127.0.0.1:2181";
		String nameSpace = "auto-pull-conf";

		RetryPolicy retryPolicy =
				new ExponentialBackoffRetry(1000, 3);
		client = CuratorFrameworkFactory.builder()
				.connectString(connectString)
				.sessionTimeoutMs(5000)
				.connectionTimeoutMs(5000)
				.retryPolicy(retryPolicy)
				.namespace(nameSpace)
				.build();
		client.start();

		client.create()
				.withMode(CreateMode.EPHEMERAL)
				.forPath(clientPath);

		cache = CuratorCache.build(client, clientPath);
		final CuratorCacheListener listener = CuratorCacheListener.builder()
				.forChanges((oldNode, node) -> {
					System.out.printf("Node changed. Old: [%s] New: [%s]", oldNode, node);
					try {
						DataSourceConfig.setConnection();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}).build();
		cache.listenable().addListener(listener);
		cache.start();
	}

}
